package com.geek688.auxiliarytool.ui;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.geek688.auxiliarytool.util.ReadDocumentUtil;

/**
 * WordUI
 */
public class WordUI {
	
//	static String[] names = {"字段名","数据类型","非空","默认值","备注"};
	static String[] cols = {"colName","type","isNull","defaultVal","remark"};
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		List<Map<String, Object>>  data = new ArrayList<>();
//		"CREATE TABLE `table` (\r\n" + 
//				"  `pk` pkType NOT NULL COMMENT 'pkRemark',\r\n" + 
//				"  `status` tinyint(4) DEFAULT NULL COMMENT '状态',\r\n" + 
//				"  PRIMARY KEY (`pk`)\r\n" + 
//				") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='tableRemark';";
		try {
			String docFileText = ReadDocumentUtil.getTextFromWord("C:\\Users\\hanjiefei\\Desktop\\旭恒绿色包装园建设管理平台.doc");
			docFileText = docFileText.replaceAll("\\t+", "###");
			docFileText = docFileText.replaceAll("\r\n+", "huanhang");
			docFileText = docFileText.replaceAll("\n+", "huanhang");
			
			String[] split = docFileText.split("表名");
			
			for(String s : split) {
				if (s==null || s=="") {
					continue;
				}
				String[] split2 = s.split("字段名###数据类型###非空###默认值###备注");
				if (split2[0].contains("（")) {
					String tablename = split2[0].split("（")[0];
					String tableRemark = split2[0].split("（")[1].split("）、")[0];
					Map<String, Object> map = new HashMap<>();
					map.put("tableName", tablename);
					map.put("tableRemark", tableRemark.replaceAll("）|\\)", ""));
					data.add(map);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		testWord(data);
		
		for(Map<String, Object> m : data) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(String.format("CREATE TABLE `%s` (", m.get("tableName"))+"\n");
			List<Map<String, Object>> maps = (List<Map<String, Object>>) m.get("column");
			String pk = "";
			for(int index= 0;index<maps.size();index++) {
				Map<String, Object> col = maps.get(index);
				String isNull = (String) col.get("isNull");
				if (isNull != null) {
					if ("NO".equals(isNull)) {
						isNull = "NOT NULL";
					}else {
						isNull = "";
					}
				}else {
					isNull = "";
				}
				String defaultVal = (String) col.get("defaultVal");
				if (defaultVal != null) {
					if ("(NULL)".equals(defaultVal)) {
						defaultVal = "";
					}
				}else {
					defaultVal = "";
				}
				if (index==0) {
					pk = (String) col.get("colName");
					buffer.append("\t"+String.format("`%s` %s NOT NULL COMMENT '%s',", col.get("colName"),col.get("type"),col.get("remark"))+"\n");
				}else {
					if ("".equals(defaultVal)) {
						buffer.append("\t"+String.format("`%s` %s %s COMMENT '%s',", col.get("colName"),col.get("type"),isNull,col.get("remark"))+"\n");
					}else {
						buffer.append("\t"+String.format("`%s` %s %s DEFAULT %s COMMENT '%s',", col.get("colName"),col.get("type"),isNull,defaultVal,col.get("remark"))+"\n");
					}
				}
			}
			buffer.append("\t"+String.format("PRIMARY KEY (`%s`)", pk)+"\n");
			buffer.append(String.format(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='%s';", m.get("tableRemark"))+"\n");
			System.err.println(buffer);
		}
		
		
	}
	
	 public static void testWord(List<Map<String, Object>>  data ){  
	        try{  
	            FileInputStream in = new FileInputStream("C:\\Users\\hanjiefei\\Desktop\\旭恒绿色包装园建设管理平台.doc");//载入文档  
	            POIFSFileSystem pfs = new POIFSFileSystem(in);     
	            @SuppressWarnings("resource")
				HWPFDocument hwpf = new HWPFDocument(pfs);
	            Range range = hwpf.getRange();//得到文档的读取范围  
	            TableIterator it = new TableIterator(range);  
	           //迭代文档中的表格  
	            int yy = 0;
	            while (it.hasNext()) {     
	                Table tb = (Table) it.next();   
	                Map<String, Object> map = data.get(yy++);
	                //迭代行，默认从0开始  
//	                System.out.println(yy);
	                List<Map<String, Object>>  column = new ArrayList<>();
	                for (int i = 0; i < tb.numRows(); i++) {     
	                    TableRow tr = tb.getRow(i);
	                    if (i==0) {
							continue;
						}
	                    //迭代列，默认从0开始  
//	                    System.out.println("numCells   "+tr.numCells());
	                    Map<String, Object> maps = new HashMap<>();
	                    for (int j = 0; j < tr.numCells(); j++) {     
	                        TableCell td = tr.getCell(j);//取得单元格  
	                        //取得单元格的内容  
//	                        System.out.println("cell   "+td.numParagraphs());
	                        
	                        for(int k=0;k<td.numParagraphs();k++){     
	                            Paragraph para =td.getParagraph(k);  
	                            String s = para.text().trim();  
	                            s = s.replaceAll("", "");
	                            s = s.replaceAll("\\( | \\)", "");
	                            s = s.replaceAll("\r\n", "");
	                            s = s.replaceAll("\\n", "");
	                            s = s.replaceAll("\\s+", "");
//	                            System.out.println("cell   "+cols[j]+ s);
	        					maps.put(cols[j], s);
	                        } //end for      
	                       
	                    }   //end for  
	                     
	                    column.add(maps);
	                }   //end for  
	                map.put("column", column);
	            } //end while  
	        }catch(Exception e){  
	            e.printStackTrace();  
	        }  
	    }//end me
}
